# -*- coding:utf-8 -*-

from fastapi import FastAPI, Request
from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError

from starlette.exceptions import HTTPException

from utils.logger import logger

def handle_exception(app: FastAPI):
    """
    Add exception handlers to the FastAPI app.
    """
    
    # 自定义服务异常
    @app.exception_handler(ServiceException)
    async def service_exception_handler(request: Request, exc: ServiceException):
        logger.error(exc.message)
        return JSONResponse({
            "code": exc.code,
            "message": jsonable_encoder(exc.message),
            "success": False,
            "data": None,
        }, 200)
    
    # 处理其他http请求异常
    @app.exception_handler(HTTPException)
    async def http_exception_handler(request: Request, exc: HTTPException):
        return JSONResponse(
            content=jsonable_encoder({'code': exc.status_code, 'msg': exc.detail}), status_code=exc.status_code
        )

    # 处理其他异常
    @app.exception_handler(Exception)
    async def exception_handler(request: Request, exc: Exception):
        logger.exception(exc)
        return JSONResponse({
            "code": 500,
            "message": str(exc),
            "success": False,
            "data": None,
        }, 200)
    
    @app.exception_handler(401)
    async def http_401_exception_handler(request: Request, exc: HTTPException):
        return JSONResponse(
            content=jsonable_encoder({'code': exc.status_code, 'msg': exc.detail}), status_code=exc.status_code
        )
    @app.exception_handler(404)
    async def http_404_exception_handler(request: Request, exc: HTTPException):
        return JSONResponse(
            content=jsonable_encoder({'code': exc.status_code, 'msg': exc.detail}), status_code=exc.status_code
        )
    @app.exception_handler(405)
    async def http_405_exception_handler(request: Request, exc: HTTPException):
        return JSONResponse(
            content=jsonable_encoder({'code': exc.status_code, 'msg': exc.detail}), status_code=exc.status_code
        )



class ServiceException(Exception):
    """
    自定义服务异常ServiceException
    """
    def __init__(self, code: int = 500, data: str = None, message: str = None):
        self.code = code
        self.data = data
        self.message = message
